package com.gzhryc.shared_device.oem.h5.mng.controllers.config;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.poi.ss.usermodel.Workbook;

import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.TreeResult;
import com.gzhryc.common.excel.ExcelTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.dictionary.dao.db.Country;
import com.gzhryc.dictionary.dao.db.CountryArea;
import com.gzhryc.dictionary.dao.enums.CountryAreaEnum;
import com.gzhryc.dictionary.services.CountryAreaService;
import com.gzhryc.dictionary.services.CountryService;
import com.gzhryc.dictionary.services.WxCountryAreaHelper;
import com.gzhryc.dictionary.services.dto.CountryAreaSearch;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class CountryAreaController {

	@Route("/config/country/area/list.html")
	public String list(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("typeList", CountryAreaEnum.Type.values());
		Long countryId = WebUtils.getLong(request, "countryId");
		if(countryId != null) {
			Country country = CountryService.self().getById(countryId);
			if(country != null) {
				request.setAttribute("country", country);
			}
		}
		return "/config/country/area/list.html";
	}
	
	@Route("/config/country/area/list.data")
	public ListResult<CountryArea> listData(HttpServletRequest request){
		ListResult<CountryArea> result = new ListResult<CountryArea>(DtoConstants.SUCCESS);
		CountryAreaSearch search = WebUtils.getParameter(request,CountryAreaSearch.class);
		
		Integer pageNo = WebUtils.getInteger(request, "page",1);
		Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
		if(search.getCountryId() != null) {
			CountryAreaService chinaAreaSer = CountryAreaService.self();
			result.getBody().setTotal(chinaAreaSer.countBySearch(search));
			List<CountryArea> data = chinaAreaSer.findBySearch(search, pageNo, pageLimit);
			result.getBody().setData(data);
		}
		return result;
	}
	
	/**
	 * 获取中国地区树结构
	 * @param request
	 * @param response
	 * @return
	 */
	@Route("/config/china/area/tree/select.data")
	public TreeResult<CountryArea> select(HttpServletRequest request,HttpServletResponse response){
		TreeResult<CountryArea> result = new TreeResult<CountryArea>(DtoConstants.SUCCESS);
		List<CountryArea> data = CountryAreaService.self().findChinaTree();
		result.getBody().setData(data);
		return result;
	}
	
	@Route("/config/country/area/get.do")
	public AjaxResult get(HttpServletRequest request,HttpServletResponse response){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"获取失败");
		Long id = WebUtils.getLong(request, "id");
		if(id != null) {
			CountryArea chinaArea = CountryAreaService.self().getById(id);
			if(chinaArea != null) {
				result.setCode(DtoConstants.SUCCESS, null);
				result.setBody(chinaArea);
			}
		}
		return result;
	}
	
	@Route("/config/country/area/add.html")
	public String add(HttpServletRequest request,HttpServletResponse response){
		Long parentId = WebUtils.getLong(request, "parentId");
		if(parentId != null) {
			CountryArea parent = CountryAreaService.self().getById(parentId);
			if(parent != null) {
				request.setAttribute("parent", parent);
			}
		}
		request.setAttribute("typeList", CountryAreaEnum.Type.values());
		return "/config/country/area/edit.html";
	}
	
	@Route("/config/country/area/add.do")
	public AjaxResult doAdd(HttpServletRequest request,HttpServletResponse response){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败");
		CountryArea chinaArea = WebUtils.getParameter(request, CountryArea.class);
		try {
			if(CountryAreaService.self().add(chinaArea)) {
				result.setCode(DtoConstants.SUCCESS, null);
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	@Route("/config/country/area/update.html")
	public String update(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("typeList", CountryAreaEnum.Type.values());
		Long id = WebUtils.getLong(request, "id");
		if(id != null) {
			CountryArea countryArea = CountryAreaService.self().getById(id);
			WebUtils.setAttribute(request, countryArea);
			if(countryArea.getParentId() != null) {
				CountryArea parent = CountryAreaService.self().getById(countryArea.getParentId());
				request.setAttribute("parent", parent);
			}
		}
		request.setAttribute("typeList", CountryAreaEnum.Type.values());
		return "/config/country/area/edit.html";
	}
	
	@Route("/config/country/area/update.do")
	public AjaxResult doUpdate(HttpServletRequest request,HttpServletResponse response){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败");
		CountryArea chinaArea = WebUtils.getParameter(request, CountryArea.class);
		try {
			if(CountryAreaService.self().updateNotNull(chinaArea)) {
				result.setCode(DtoConstants.SUCCESS, null);
			}
		} catch (LogicException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@Route("/config/country/area/del.do")
	public AjaxResult delete(HttpServletRequest request,HttpServletResponse response){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"获取失败");
		Long id = WebUtils.getLong(request, "id");
		if(id != null) {
			if(CountryAreaService.self().deleteById(id)) {
				result.setCode(DtoConstants.SUCCESS, null);
			}
		}
		return result;
	}
	
	/**
	 * 导出
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@Route(value = "/config/country/area/exportExcel.html")
	public void doExportToExcel(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
		ListResult<Country> result = new ListResult<Country>(DtoConstants.SUCCESS);
		CountryAreaSearch search = WebUtils.getParameter(request,CountryAreaSearch.class);
		String[] titles = {  "地区编号","国家ID","地区简称","地区全称","拼音","别称","类型","类型名","优先级","状态","状态名"
				,"LeftNum","RightNum","RootId","ParentId","更新时间","创建时间"};
		List<Object[]> data = new ArrayList<>();
		if(search.getCountryId() != null) {
			CountryAreaService chinaAreaSer = CountryAreaService.self();
			result.getBody().setTotal(chinaAreaSer.countBySearch(search));
			List<CountryArea> dataList = chinaAreaSer.findBySearch(search, null, null);
			if(dataList != null) {
				for (CountryArea entity : dataList) {
					Object[] objects = new Object[17];
					objects[16] = entity.getCreateDate();
					objects[15] = entity.getUpdateDate();
					objects[14] = entity.getParentId();
					objects[13] = entity.getRootId();
					objects[12] = entity.getRightNum();
					objects[11] = entity.getLeftNum();
					objects[10] = entity.getStatusName();
					objects[9] = entity.getStatus();
					objects[8] = entity.getPriority();
					objects[7] = entity.getTypeName();
					objects[6] = entity.getType();
					objects[5] = entity.getCode(); 
					objects[4] = entity.getPinyin();
					objects[3] = entity.getFullName();
					objects[2] = entity.getName();
					objects[1] = entity.getCountryId();
					objects[0] = entity.getId();
					data.add(objects);
				}
			}
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String name = format.format(new Date());
		WebUtils.exportExcel(response, name);
		ExcelTools.export(response.getOutputStream(), "地区信息", null, titles, data);
	}
	
	//导入
	@Route(value = "/config/country/area/uploadExcel.do")
	public AjaxResult uploadExcel(HttpServletRequest request, FileItem file,HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "导入失败，请稍后再试！");
		Long countryId = Long.parseLong(request.getHeader("countryId"));
		try {
			Workbook workbook = ExcelTools.readExcelToWorkbook(file.getName(), file.getInputStream());
			List<CountryArea> areaList = ExcelTools.readExcel(workbook, CountryArea.class,
					new String[] { "id","countryId","name","fullName","pinyin","code","type","typeName","priority","status","statusName"
							,"leftNum","rightNum","rootId","parentId"},
					0, 1);
			int i = 0;
			if (areaList != null && areaList.size() > 0) {
				//记录插入失败的记录
				List<CountryArea> failList = new ArrayList<CountryArea>();
				for (CountryArea area : areaList) {
					if(area.getCountryId()==null) area.setCountryId(countryId);
					CountryArea temp = CountryAreaService.self().getById(area.getId());
					if(temp==null) {
						if(!CountryAreaService.self().add(area)) {
							failList.add(area);
							continue;
						}
					}else {
						if(!CountryAreaService.self().updateNotNull(area)) {
							failList.add(area);
							continue;
						}
					}
					i++;
				}
				//将由于parentId 造成插入失败的记录 重新插入
				if(failList.size()>0) {
					for (CountryArea area : failList) {
						if(area.getCountryId()==null) area.setCountryId(countryId);
						CountryArea temp = CountryAreaService.self().getById(area.getId());
						if(temp==null) {
							if(!CountryAreaService.self().add(area)) {
								System.out.println("添加id"+area.getId()+"时错误");
								continue;
							}
						}else {
							if(!CountryAreaService.self().updateNotNull(area)) {
								System.out.println("修改id"+area.getId()+"时错误");
								continue;
							}
						}
						i++;
					}
				}
			}
			if (i > 0) {
				result.setCode(DtoConstants.SUCCESS, "成功导入"+i+"条记录");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Route(value = "/config/country/area/uploadJson.do")
	public AjaxResult uploadJson(HttpServletRequest request, FileItem file,HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "导入失败，请稍后再试！");
		Long countryId = Long.parseLong(request.getHeader("countryId"));
		try {
			WxCountryAreaHelper.JsonEntity jsonEntity = JsonTools.fromJson(file.getInputStream(), WxCountryAreaHelper.JsonEntity.class);
			List<CountryArea> countryAreaList = WxCountryAreaHelper.importJson(countryId, jsonEntity);
			if (countryAreaList != null && countryAreaList.size() > 0) {
				for (CountryArea province : countryAreaList) {
					CountryAreaService.self().add(province);
					if(province.getChildren() != null && province.getChildren().size() > 0){
						for (CountryArea city : province.getChildren()) {
							city.setParentId(province.getId());
							CountryAreaService.self().add(city);
							if(city.getChildren() != null && city.getChildren().size() > 0) {
								for (CountryArea cityArea : city.getChildren()) {
									cityArea.setParentId(city.getId());
									CountryAreaService.self().add(cityArea);
								}
							}
						}
					}
				}
				result.setCode(DtoConstants.SUCCESS, null);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
